package com.dsit.sq;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dsit.sq.mydefineview.LongColorfulProgressBar;
import com.dsit.sq.mydefineview.PullToRefreshBase;
import com.dsit.sq.mydefineview.PullToRefreshScrollView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

/**
 * 氢瓶状态　界面
 * Created by dsit_dev04 on 2016/10/9.
 */
public class QingActivity extends BaseActivity implements OnClickListener {
    private ImageView qingReturnImagEView;
    private TextView qingDataTextView;
    private TextView qingStatusTextView;
    private LongColorfulProgressBar qingProgressView;
    private TextView qingLowPreDataTextView;
    private TextView qingLowPreStatusTextView;
    private LongColorfulProgressBar qingLowPreProgressView;
    private TextView qingPressureDataTextView;
    private TextView qingPressureStatusTextView;
    private LongColorfulProgressBar qingPressureProgressView;
    private TextView qingTempOneDataTextView;
    private TextView qingTempOneStatusTextView;
    private LongColorfulProgressBar qingTempOneProgressView;
    private TextView qingTempTwoDataTextView;
    private TextView qingTempTwoStatusTextView;
    private LongColorfulProgressBar qingTempTwoProgressView;
    private TextView qingMiddlePreDataTextView;
    private TextView qingMiddlePreStatusTextView;
    private LongColorfulProgressBar qingMiddlePreProgressView;
    private TextView dtcClassDataTextView;
    private TextView dtcClassStatusTextView;
    private LongColorfulProgressBar dtcClassProgressView;
    private TextView dtcRegisterDataTextView;
    private TextView dtcRegisterStatusTextView;
    private LongColorfulProgressBar dtcRegisterProgressView;
    private TextView dtcCodeDataTextView;
    private TextView dtcCodeStatusTextView;
    private LongColorfulProgressBar dtcCodeProgressView;
    private TextView dtcCounterDataTextView;
    private TextView dtcCounterStatusTextView;
    private LongColorfulProgressBar dtcCounterProgressView;
    private final int qing_soc = 7;
    private final int qing_low_pre = 39;
    private final int qing_pressure = 40;
    private final int qing_temp_one = 41;
    private final int qing_temp_two = 42;
    private final int qing_middle_pre = 43;
    private final int qing_dtc_class = 44;
    private final int qing_dtc_register = 45;
    private final int qing_dtc_code = 46;
    private final int qing_dtc_counter = 47;

    private PullToRefreshScrollView pullQingScrollView;//　下拉刷新
    private LinearLayout qingLinearLayout;
    private ScrollView qingScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_qing);
        qingReturnImagEView = (ImageView) findViewById(R.id.qing_return_button);
        qingReturnImagEView.setOnClickListener(this);

        ProtoMsgDispatcher.getInstance().addDataListener(dataListener);

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        qingLinearLayout =(LinearLayout) inflater.inflate(R.layout.qing_layout,null);

        qingDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_data_text);
        qingStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_status_text);
        qingProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_status_progress);
        qingLowPreDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_lowpre_data_text);
        qingLowPreStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_lowpre_status_text);
        qingLowPreProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_lowpre_status_progress);
        qingPressureDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_pressure_data_text);
        qingPressureStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_pressure_status_text);
        qingPressureProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_pressure_status_progress);
        qingTempOneDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_tempone_data_text);
        qingTempOneStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_tempone_status_text);
        qingTempOneProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_tempone_status_progress);
        qingTempTwoDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_temptwo_data_text);
        qingTempTwoStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_temptwo_status_text);
        qingTempTwoProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_temptwo_status_progress);
        qingMiddlePreDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_middlepre_data_text);
        qingMiddlePreStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_middlepre_status_text);
        qingMiddlePreProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_middlepre_status_progress);
        dtcClassDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_dtcclass_data_text);
        dtcClassStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_dtcclass_status_text);
        dtcClassProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_dtcclass_status_progress);
        dtcRegisterDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_dtcregister_data_text);
        dtcRegisterStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_dtcregister_status_text);
        dtcRegisterProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_dtcregister_status_progress);
        dtcCodeDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_dtccode_data_text);
        dtcCodeStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_dtccode_status_text);
        dtcCodeProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_dtccode_status_progress);
        dtcCounterDataTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_dtccounter_data_text);
        dtcCounterStatusTextView = (TextView) qingLinearLayout.findViewById(R.id.qing_dtccode_status_text);
        dtcCounterProgressView = (LongColorfulProgressBar) qingLinearLayout.findViewById(R.id.qing_dtccounter_status_progress);

        pullQingScrollView = (PullToRefreshScrollView)findViewById(R.id.qing_pullscroll);
        pullQingScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                new GetDataTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

            }
        });
        qingScrollView = pullQingScrollView.getRefreshableView();
        qingScrollView.setVerticalScrollBarEnabled(false);
        qingScrollView.addView(qingLinearLayout);
//        powerBatteryScrollView.addView(createTextView());
        setLastUpdateTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ProtoMsgDispatcher.getInstance().removeDataListener(dataListener);
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
            pullQingScrollView.onPullDownRefreshComplete();
            setLastUpdateTime();
            super.onPostExecute(result);
        }
    }
    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        pullQingScrollView.setLastUpdatedLabel(text);
    }

    private SimpleDateFormat mDateFormat = new SimpleDateFormat("HH:mm:ss");
    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }

        return mDateFormat.format(new Date(time));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.qing_return_button:
                finish();
            default:
                break;
        }
    }

    private DataListener dataListener = new DataListener() {
        @Override
        public void onUpdateData(ProtoMessage msg) {
            if(msg.getActionId().equals("canbus.msg")){
                byte[] data = msg.getContentData();
                Log.i("main_activity", "收到回调");
                String str = new String(data, 0, data.length);
                try {
                    JSONArray array = new JSONArray(str);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = (JSONObject) array.get(i);
                        int id = object.getInt("id");
                        Double value = object.getDouble("value");
                        Bundle bundle = new Bundle();
                        Message message = new Message();
                        message.setData(bundle);
                        bundle.putDouble("value", value);
                        switch (id) {
                            case qing_soc:
                                message.what = qing_soc;
                                mHandler.sendMessage(message);
                                break;
                            case qing_low_pre:
                                message.what = qing_low_pre;
                                mHandler.sendMessage(message);
                                break;
                            case qing_pressure:
                                message.what = qing_pressure;
                                mHandler.sendMessage(message);
                                break;
                            case qing_temp_one:
                                message.what = qing_temp_one;
                                mHandler.sendMessage(message);
                                break;
                            case qing_temp_two:
                                message.what = qing_temp_two;
                                mHandler.sendMessage(message);
                                break;
                            case qing_middle_pre:
                                message.what = qing_middle_pre;
                                mHandler.sendMessage(message);
                                break;
                            case qing_dtc_class:
                                message.what = qing_dtc_class;
                                mHandler.sendMessage(message);
                                break;
                            case qing_dtc_register:
                                message.what = qing_dtc_register;
                                mHandler.sendMessage(message);
                                break;
                            case qing_dtc_code:
                                message.what = qing_dtc_code;
                                mHandler.sendMessage(message);
                                break;
                            case qing_dtc_counter:
                                message.what = qing_dtc_counter;
                                mHandler.sendMessage(message);
                                break;
                            default:
                                break;
                        }
                        Log.i("data", object.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /*
    在UI线程显示界面数据
     */
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message message) {
            try {
                Bundle bundle = new Bundle();
                bundle = message.getData();
                switch (message.what) {
                    case qing_soc:
                        int progress = (int) ((float) (bundle.getDouble("value") / 127.5) * 100);
                        qingProgressView.setProgress(progress);
                        qingDataTextView.setText(formatDouble(bundle.getDouble("value")) + "%");
                        break;
                    case qing_low_pre:
                        int lowPreProgress = (int) ((float) (bundle.getDouble("value") / 500) * 100);
                        qingLowPreProgressView.setProgress(lowPreProgress);
                        qingLowPreDataTextView.setText(formatDouble(bundle.getDouble("value")) + "kPa");
                        break;
                    case qing_pressure:
                        int pressureProgress = (int) ((float) (bundle.getDouble("value") / 102.2) * 100);
                        qingPressureProgressView.setProgress(pressureProgress);
                        qingPressureDataTextView.setText(formatDouble(bundle.getDouble("value")) + "MPa");
                        break;
                    case qing_temp_one:
                        int tempOneProgress = (int) ((float) (bundle.getDouble("value") / 150) * 100);
                        qingTempOneProgressView.setProgress(tempOneProgress);
                        qingTempOneDataTextView.setText(formatDouble(bundle.getDouble("value")) + "℃");
                        break;
                    case qing_temp_two:
                        int tempTwoprogress = (int) ((float) (bundle.getDouble("value") / 200) * 100);
                        qingTempTwoProgressView.setProgress(tempTwoprogress);
                        qingTempTwoDataTextView.setText(formatDouble(bundle.getDouble("value")) + "℃");
                        break;
                    case qing_middle_pre:
                        int middlePreProgress = (int) ((float) (bundle.getDouble("value") / 2.55) * 100);
                        qingMiddlePreProgressView.setProgress(middlePreProgress);
                        qingMiddlePreDataTextView.setText(formatDouble(bundle.getDouble("value")) + "MPa");
                        break;
                    case qing_dtc_class:
                        int dtcClassProgress = (int) ((float) (bundle.getDouble("value") / 31) * 100);
                        dtcClassProgressView.setProgress(dtcClassProgress);
                        dtcClassDataTextView.setText(formatDouble(bundle.getDouble("value")));
                        break;
                    case qing_dtc_register:
                        int dtcRegisterProgress = (int) ((float) (bundle.getDouble("value") / 7) * 100);
                        dtcRegisterProgressView.setProgress(dtcRegisterProgress);
                        dtcRegisterDataTextView.setText(formatDouble(bundle.getDouble("value")));
                        break;
                    case qing_dtc_code:
                        int dtcCodeProgress = (int) ((float) (bundle.getDouble("value") / 65535) * 100);
                        dtcCodeProgressView.setProgress(dtcCodeProgress);
                        dtcCodeDataTextView.setText(formatDouble(bundle.getDouble("value")));
                        break;
                    case qing_dtc_counter:
                        int dtcCounterProgress = (int) ((float) (bundle.getDouble("value") / 255) * 100);
                        dtcCounterProgressView.setProgress(dtcCounterProgress);
                        dtcCounterDataTextView.setText(formatDouble(bundle.getDouble("value")));
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    private String formatDouble(Double data) {
        DecimalFormat format = new DecimalFormat("0.00");
        return format.format(data);
    }
}
